<template>
  <div class="wrapper">
    <xr-header
      ft-top="0"
      placeholder="请输入组织部门名称"
      show-search
      @search="searchClick">
      <template slot="label">
        组织管理<el-tooltip
          v-if="hrmUserType === 2"
          effect="dark"
          placement="top"
          style="margin-left: 8px;"
          content="仅展示您管理范围内的员工">
          <i class="wk wk-help wk-help-tips" />
        </el-tooltip>
      </template>
      <template slot="bottom-ft">
        <wk-toggle-button
          v-model="showType">
          <wk-toggle-item
            v-for="item in [{name:'列表视图', value: 'table', icon: 'wk wk-icon-three-line'}, {name:'架构视图', value: 'tree', icon: 'wk wk-icon-org-solid'}]"
            :key="item.value"
            :label="item.name"
            :value="item.value">
            {{ item.name }}<i :class="item.icon" />
          </wk-toggle-item>
        </wk-toggle-button>
      </template>
<!--      <template slot="ft">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          @click="orgEmployeeChangeClick">机构人员调整-->
<!--        </el-button>-->
<!--      </template>-->
      <template slot="ft">
        <el-button
          v-if="createAuth"
          type="primary"
          @click="gzwDeptPushDataClick">国资委部门同步
        </el-button>
      </template>
      <template slot="ft">
        <el-button
          v-if="createAuth"
          type="primary"
          @click="deptEmployeeDataTotalClick">组织人员数据统计
        </el-button>
      </template>
      <template v-if="showType != 'table'" slot="ft">
        <el-button
          v-if="createAuth"
          type="primary"
          @click="deptPrintClick">打印
        </el-button>
      </template>
      <template slot="ft">
        <el-button
          v-if="createAuth"
          type="primary"
          @click="deptImportClick">导入
        </el-button>
      </template>
      <template slot="ft">
        <el-button
          v-if="createAuth"
          type="primary"
          @click="deptExportClick">导出
        </el-button>
      </template>
      <template slot="ft">
        <el-button
          v-if="createAuth"
          type="primary"
          @click="deptPushDataClick">组织数据同步
        </el-button>
      </template>
      <template slot="ft">
        <el-button
          v-if="createAuth"
          type="primary"
          @click="createClick">新建组织
        </el-button>
      </template>
    </xr-header>
    <div
      v-loading="loading"
      :class="{'is-org' : showType === 'tree'}"
      class="wrapper-main">
      <tree-table
        v-if="showType == 'table'"
        :data="list"
        :height="tableHeight"
        :columns="columns"
        :eval-args="[null, null, fieldFormatter]"
        :cell-class-name="cellClassName"
        stripe
        class="el-table-header--white"

        @row-click="handleRowClick" />
      <div
        v-else
        ref="imgTransf"
        :style="{height: `${tableHeight}px`}"
        class="wk-org-tree">
        <dept-org-tree
          :data="orgTreeData"
          collapsable
          :label-class-name="orgTreeClass"
          :props="{label: 'name', children: 'children', expand: 'expand'}"
          :render-content="renderContent"
          @on-node-click="orgTreeClick"
          @on-expand="onExpand"
        />
        <wk-toggle-button
          v-if="showImgTransf"
          style="position: absolute;right: 47px; top: 130px;"
          v-model="orgShowType"
          @input="showTypeChange">
          <wk-toggle-item
            v-for="item in [{name:'只显示单位', value: 'onlyUnit', icon: 'wk wk-icon-three-line'}, {name:'显示全部', value: 'all', icon: 'wk wk-icon-org-solid'}]"
            :key="item.value"
            :label="item.name"
            :value="item.value">
            {{ item.name }}<i :class="item.icon" />
          </wk-toggle-item>
        </wk-toggle-button>
      </div>
    </div>

    <dept-add-dialog
      v-if="deptAddDialogShow"
      :visible.sync="deptAddDialogShow"
      @success="getDeptList"
    />

    <dept-detail
      v-if="detailShow"
      :id="detailId"
      @close="detailShow = false"
      @edit-success="getDeptList"
      @delete-success="getDeptList"
    />

    <!--  导出  -->
    <el-dialog title="选择导出公司"
               :visible.sync="exportOpen"
               width="25%"
               v-if="exportOpen"
               append-to-body
               v-loading="exportLoading"
               element-loading-text="拼命加载中"
    >
      <el-select
          v-model="deptIdList"
          filterable
          multiple
          placeholder="请选择选择导出公司"
          style="width: 60%"
      >
        <el-option
            v-for="item in deptList"
            :key="item.deptId"
            :label="item.name"
            :value="item.deptId"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportOpen = false">取 消</el-button>
        <el-button type="primary" @click="exportDept">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量导入 -->
    <bulk-import-dept
        :show="bulkImportShow"
        @close="bulkImportShow=false"
        @success="addSuccess" />


    <!--  人员数据统计  -->
    <el-dialog :title="employeeDataTotal.title"
               :visible.sync="employeeDataTotal.open"
               width="75%"
               v-if="employeeDataTotal.open"
               append-to-body
               element-loading-text="拼命加载中"
    >
      <div class="dialog-content" style="height:600px;overflow-y: auto;padding: 20px;">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="" prop="totalDate">
            <el-date-picker
              v-model="totalDate"
              type="month"
              :clearable=false
              :editable=false
              value-format="yyyy-MM"
              placeholder="选择年月">
            </el-date-picker>
          </el-form-item>
            <el-button type="primary" @click="handleQuery">搜 索</el-button>
        </el-form>
        <el-table
          v-loading="employeeDataTotal.loading"
          :default-expand-all="employeeDataTotal.expand"
          :expand-row-keys="expandRowKeys"
          :data="employeeDataTotal.list"
          style="width: 100%;margin-bottom: 20px;"
          row-key="deptId"
          border
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column show-overflow-tooltip prop="name" label="组织部门名称"/>
          <el-table-column show-overflow-tooltip align="center" prop="deptType" label="组织类型" :formatter="deptTypeFormatter"/>
          <el-table-column show-overflow-tooltip align="center" prop="dataProgress" label="数据完整度">
            <template slot-scope="scope">
              <div class="progress-wrapper" @click="handleDataProgress(scope.row)">
                <el-progress :text-inside="true" v-if="scope.row.dataProgress > 50" :stroke-width="25" :percentage="scope.row.dataProgress" status="success"></el-progress>
                <el-progress :text-inside="true" v-else :stroke-width="25" :percentage="scope.row.dataProgress" status="exception"></el-progress>
              </div>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip align="center" prop="changeNumber" label="修改频次">
            <template slot-scope="scope">
              <a @click="handleChangeNumber(scope.row)" style="color: blue; cursor: pointer">{{ scope.row.changeNumber }}</a>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip align="center" prop="mobilizeNumber" label="人员异动数">
            <template slot-scope="scope">
              <a @click="handleMobilizeNumber(scope.row)" style="color: blue; cursor: pointer">{{ scope.row.mobilizeNumber }}</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="employeeDataTotal.open = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!--  人员数据统计详情  -->
    <el-dialog :title="totalDetail.title"
               :visible.sync="totalDetail.open"
               width="75%"
               v-if="totalDetail.open"
               append-to-body
               element-loading-text="拼命加载中"
    >
      <div class="dialog-content" style="height:600px;overflow-y: auto;padding: 20px;">
        <el-table
          v-loading="totalDetail.loading"
          :data="totalDetail.list"
          style="width: 100%;margin-bottom: 20px;">
          <el-table-column show-overflow-tooltip label="姓名" align="center" prop="employeeName"/>
          <el-table-column show-overflow-tooltip label="数据完整度" align="center" prop="dataProgress">
            <template slot-scope="scope">
              <el-progress :text-inside="true" v-if="scope.row.dataProgress > 50" :stroke-width="25" :percentage="scope.row.dataProgress" status="success"></el-progress>
              <el-progress :text-inside="true" v-else :stroke-width="25" :percentage="scope.row.dataProgress" status="exception"></el-progress>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="性别" align="center" prop="sex" :formatter="sexFormatter"/>
          <el-table-column show-overflow-tooltip label="任职机构" align="center" prop="orgName"/>
          <el-table-column show-overflow-tooltip label="任职部门" align="center" prop="deptName"/>
          <el-table-column show-overflow-tooltip label="职务" align="center" prop="jobTitle"/>
          <el-table-column show-overflow-tooltip label="职位层级" align="center" prop="jobLevel"/>
          <el-table-column show-overflow-tooltip label="政治面貌" align="center" prop="polId"/>
          <el-table-column show-overflow-tooltip label="在岗状态" align="center" prop="postStatus"/>
          <el-table-column show-overflow-tooltip label="用工形式" align="center" prop="workForms"/>
          <el-table-column show-overflow-tooltip label="手机" align="center" prop="mobile"/>
          <el-table-column show-overflow-tooltip label="身份证号" align="center" prop="idNumber"/>
        </el-table>
      </div>
      <div class="p-contianer">
        <el-pagination :current-page="queryProgressParams.page" :page-sizes="pageSizes" :page-size.sync="queryProgressParams.limit" :total="totalDetail.total"
                       class="p-bar" layout="total, sizes, prev, pager, next, jumper" @size-change="handleIntegritySizeChange"
                       @current-change="handleIntegrityCurrentChange" />
      </div>
    </el-dialog>

    <!--  人员修改记录   -->
    <el-dialog :title="record.title"
               :visible.sync="record.open"
               width="75%"
               v-if="record.open"
               append-to-body
               element-loading-text="拼命加载中"
    >
      <div class="dialog-content" style="height:600px;overflow-y: auto;padding: 20px;">
        <el-table
          v-loading="record.loading"
          :data="record.list"
          style="width: 100%;margin-bottom: 20px;">
          <el-table-column show-overflow-tooltip label="操作人" align="center" prop="employeeName"/>
          <el-table-column show-overflow-tooltip label="部门路径" align="center" prop="deptPath"/>
          <el-table-column show-overflow-tooltip label="操作时间" align="center" prop="createTime"/>
          <el-table-column show-overflow-tooltip label="操作内容" align="center" prop="remark"/>
        </el-table>
      </div>
      <div class="p-contianer">
        <el-pagination :current-page="queryRecordParams.page" :page-sizes="pageSizes" :page-size.sync="queryRecordParams.limit" :total="record.total"
                       class="p-bar" layout="total, sizes, prev, pager, next, jumper" @size-change="handleRecordSizeChange"
                       @current-change="handleRecordCurrentChange" />
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  hrmDeptQueryTreeListAPI,
  hrmDeptPushDataAPI,
  exportHrmDeptListAPI,
  exportHrmDeptAPI,
  hrmEmployeeDataTotalAPI,
  hrmEmployeeDataIntegrityAPI,
  hrmEmployeeChangeRecordAPI,
  hrmEmployeeMobilizeRecordAPI,
  hrmOrgEmployeeChangeAPI,
} from '@/api/hrm/dept'

import { WkToggleButton, WkToggleItem } from '@/components/NewCom/WkToggleButton/index'
import TreeTable from './TreeTable/index'
import XrHeader from '@/components/XrHeader/Search'
import DeptAddDialog from './components/DeptAddDialog'
import DeptDetail from './DeptDetail'

import { mapGetters } from 'vuex'
import {Message} from "element-ui";
import {downloadExcelWithResData} from "@/utils";
import BulkImportDept from "@/views/hrm/dept/components/BulkImportDept.vue";
import DeptOrgTree from '@/components/DeptOrgTree'
import html2Canvas from "html2canvas";
import printJS from "print-js";
import {hrmEmployeeGzwDeptSyncAPI} from "@/api/hrm/employee";

export default {
  name: 'Index',
  components: {
    BulkImportDept,
    TreeTable,
    XrHeader,
    DeptAddDialog,
    DeptDetail,
    WkToggleButton,
    WkToggleItem,
    DeptOrgTree
  },
  data() {
    return {
      totalDate: null,
      queryParams: {
        totalDate: null,
      },
      expandRowKeys: [],
      employeeDataTotal:{
        open: false,
        expand: false,
        title: '',
        loading: false,
        list: [],
      },
      pageSizes: [15, 30, 60, 100],
      queryProgressParams: {
        totalDate: null,
        deptId: null,
        page: 1,
        limit: 15,
      },
      totalDetail:{
        open: false,
        title: '',
        loading: false,
        list: [],
        total: 0,
      },
      queryRecordParams: {
        totalDate: null,
        deptId: null,
        page: 1,
        limit: 15,
      },
      record:{
        open: false,
        title: '',
        loading: false,
        list: [],
        total: 0,
      },
      showImgTransf: true,
      bulkImportShow: false,
      exportLoading: false,
      exportOpen: false,
      deptIdList: [],
      deptList: [],
      loading: false,
      tableHeight: document.documentElement.clientHeight - 220, // 表的高度
      search: '',
      showType: 'table', // tree
      list: [], // 列表
      orgShowType: 'onlyUnit',
      deptAddDialogShow: false, // 添加
      columns: [
        {
          text: '组织部门名称',
          value: 'name',
          width: 400
        },
        {
          text: '组织类型',
          value: 'deptTypeName'
        },
        /*{
          text: '在职员工',
          value: 'allNumName',
          helpType: '30',
          helpId: '277'
        },
        {
          text: '全职员工',
          value: 'fullTimeNumName',
          helpType: '30',
          helpId: '285'
        },
        {
          text: '非全职人数',
          value: 'nuFullTimeNumName',
          helpType: '30',
          helpId: '286'
        },*/
        {
          text: '实有人数',
          value: 'totalNum',
          helpType: '30',
          helpId: '277'
        },
        {
          text: '劳动合同工人数',
          value: 'contractTotal',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '劳务派遣人数',
          value: 'dispatchTotal',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '劳务外包人数',
          value: 'outsourceTotal',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '临时工人数',
          value: 'temporaryTotal',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '退休返聘人数',
          value: 'retireTotal',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '外部董事人数',
          value: 'externalTotal',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '正处编制人数',
          value: 'sectionChiefPreparation',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '正处现配备人数',
          value: 'sectionChiefNum',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '副处编制人数',
          value: 'deputySectionChiefPreparation',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '副处现配备人数',
          value: 'deputySectionChiefNum',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '正科编制人数',
          value: 'directorPreparation',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '正科现配备人数',
          value: 'directorNum',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '副科编制人数',
          value: 'deputyDirectorPreparation',
          helpType: '30',
          helpId: '286'
        },
        {
          text: '副科现配备人数',
          value: 'deputyDirectorNum',
          helpType: '30',
          helpId: '286'
        }
      ],
      // 详情
      detailShow: false,
      orgTreeData: {},
      detailId: null
    }
  },
  computed: {
    ...mapGetters([
      'hrm',
      'hrmUserType',
      'userInfo'
    ]),

    // 权限
    deptAuth() {
      return this.hrm && this.hrm.dept
    },

    // 新建
    createAuth() {
      return this.deptAuth.save
    },

    // 详情
    detailAuth() {
      return this.deptAuth.read
    },

    // orgTreeData() {
    //   if (this.list.length > 0) {
    //     return this.list[0]
    //   }
    //   return {}
    // }
  },
  watch: {
    orgShowType(val, oldVal) {
      // if(val !== oldVal) {
      //   if(val === 'all') {
      //     this.expandAll(true, this.list)
      //   } else if (val === 'onlyUnit') {
      //     this.expandOnlyUnit()
      //   }
      // }
    }
  },
  created() {
    window.onresize = () => {
      this.tableHeight = document.documentElement.clientHeight - 220
    }
    this.getDeptList()
  },
  mounted() {
  },
  methods: {
    /**
     * 点击数据完整度
     */
    handleDataProgress(row) {
      this.queryProgressParamsInit();
      this.queryProgressParams.deptId = row.deptId
      this.totalDetail.title = "人员数据完整度";
      this.handleDataProgressQuery()
      this.totalDetail.open = true;
    },

    /**
     * 查询
     */
    handleDataProgressQuery(){
      this.queryProgressParams.totalDate = this.queryParams.totalDate
      this.totalDetail.loading = true;
      hrmEmployeeDataIntegrityAPI(this.queryProgressParams).then(res => {
        this.totalDetail.loading = false;
        this.totalDetail.list = res.data.list;
        this.totalDetail.total = res.data.totalRow;
      }).catch(() => {})
    },
    /** 初始化查询参数 */
    queryProgressParamsInit(){
      this.queryProgressParams = {
        page: 1,
        limit: 15,
        deptId: null,
        totalDate: null,
      }
    },

    /** 性别格式化 */
    sexFormatter(row){
      if (row.sex == 1){
        return '男';
      }else if (row.sex == 2){
        return '女';
      }
      return row.sex;
    },

    /**
     * 更改当前页数
     */
    handleIntegrityCurrentChange(val) {
      this.queryProgressParams.page = val
      this.handleDataProgressQuery()
    },

    /**
     * 更改每页展示数量
     */
    handleIntegritySizeChange(val) {
      this.queryProgressParams.limit = val
      this.handleDataProgressQuery()
    },

    /**
     * 修改频次
     */
    handleChangeNumber(row) {
      this.queryRecordParamsInit();
      this.queryRecordParams.deptId = row.deptId
      this.record.title = "修改频次";
      this.handleChangeRecordQuery()
      this.record.open = true;
    },


    handleChangeRecordQuery(){
      this.queryRecordParams.totalDate = this.queryParams.totalDate
      this.record.loading = true;
      hrmEmployeeChangeRecordAPI(this.queryRecordParams).then(res => {
        this.record.loading = false;
        this.record.list = res.data.list;
        this.record.total = res.data.totalRow;
      }).catch(() => {})
    },

    /**
     * 异动频次
     */
    handleMobilizeNumber(row) {
      this.queryRecordParamsInit();
      this.queryRecordParams.deptId = row.deptId
      this.record.title = "人员异动数";
      this.handleMobilizeQuery()
      this.record.open = true;
    },

    handleMobilizeQuery(){
      this.queryRecordParams.totalDate = this.queryParams.totalDate
      this.record.loading = true;
      hrmEmployeeMobilizeRecordAPI(this.queryRecordParams).then(res => {
        this.record.loading = false;
        this.record.list = res.data.list;
        this.record.total = res.data.totalRow;
      }).catch(() => {})
    },

    /**
     * 更改当前页数
     */
    handleRecordCurrentChange(val) {
      this.queryRecordParams.page = val
      if (this.record.title === "人员异动数"){
        this.handleMobilizeQuery()
      }else{
        this.handleChangeRecordQuery()
      }
    },

    /**
     * 更改每页展示数量
     */
    handleRecordSizeChange(val) {
      this.queryRecordParams.limit = val
      if (this.record.title === "人员异动数"){
        this.handleMobilizeQuery()
      }else{
        this.handleChangeRecordQuery()
      }
    },

    /** 初始化查询参数 */
    queryRecordParamsInit(){
      this.queryRecordParams = {
        page: 1,
        limit: 15,
        deptId: null,
        totalDate: null,
      }
    },

    /**
     * 获取部门列表
     * @param  获取树形结构列表
     */
    getDeptList() {
      this.loading = true
      hrmDeptQueryTreeListAPI({
        type: 'tree',
        name: this.search
      })
        .then(response => {
          this.orgShowType = 'onlyUnit'
          this.list = response.data || []
          this.formatOrgTree(true)
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 展示格式化
     */
    fieldFormatter(row) {
      row.deptTypeName = {
        1: '公司',
        2: '部门'
      }[row.deptType]

      row.allNumName = `${row.myAllNum}（${row.allNum || 0}）`
      row.fullTimeNumName = `${row.myFullTimeNum}（${row.fullTimeNum || 0}）`
      row.nuFullTimeNumName = `${row.myNuFullTimeNum}（${row.nuFullTimeNum || 0}）`
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0 && this.detailAuth) {
        return 'can-visit-default'
      } else {
        return ''
      }
    },

    /**
     * 搜索
     */
    searchClick(search) {
      this.search = search
      this.getDeptList()
    },
    /**
     * 新建
     */
    createClick() {
      this.deptAddDialogShow = true
    },

    /**
     * 导入
     */
    deptImportClick(){
      this.bulkImportShow = true
    },

    /**
     * 员工数据统计
     */
    deptEmployeeDataTotalClick(){
      this.expandRowKeys = ["81100001"]
      this.totalDate = this.currentYearMonth();
      this.employeeDataTotal.title = "组织人员数据统计";
      this.handleQuery()
      this.employeeDataTotal.open = true;
    },

    orgEmployeeChangeClick(){
      hrmOrgEmployeeChangeAPI().then(res => {
        this.$message.success('调整成功')
      }).catch(() => {})
    },

    /**
     * 查询
     */
    handleQuery(){
      this.queryParams = {
        totalDate : this.totalDate,
      }
      this.employeeDataTotal.loading = true;
      hrmEmployeeDataTotalAPI(this.queryParams).then(res => {
        this.employeeDataTotal.loading = false;
        this.employeeDataTotal.list = res.data
      }).catch(() => {})
    },

    deptTypeFormatter(row, column) {
      return row.deptType === 1 ? '公司' : '部门';
    },

    /**
     * 当前年月
     */
    currentYearMonth() {
      const now = new Date();
      const year = now.getFullYear(); // 获取当前年份
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取当前月份，+1是因为getMonth()是从0开始的，padStart用于保证月份始终是两位数
      return `${year}-${month}`;
    },

    /**
     * 打印
     */
    deptPrintClick(){
      this.showImgTransf = false;
      setTimeout(() => {
        html2Canvas(this.$refs.imgTransf, {
          backgroundColor: null,
          useCORS: true,
          windowHeight: document.body.scrollHeight,
        }).then((canvas) => {
          this.showImgTransf = true;
          const url = canvas.toDataURL();
          let img = url;
          printJS({
            printable: url,
            type: "image",
            documentTitle: "打印图片",
          });
        });
      }, 200)
    },

    /**
     * addSuccess
     */
    addSuccess() {
      this.getDeptList();
    },

    /**
     * 导出
     */
    deptExportClick(){
      this.deptIdList = [];
      this.exportOpen = true;
      exportHrmDeptListAPI().then(res => {
        this.deptList = res.data;
      }).catch(() => {
      })
    },

    /**
     * 导出
     */
    exportDept() {
      if (this.deptIdList.length <= 0) {
        Message({
          message: '请选择部门',
          type: 'error'
        })
        return;
      }
      this.exportLoading = true;
      exportHrmDeptAPI({
        deptIdList: this.deptIdList
      }).then(res => {
        downloadExcelWithResData(res)
        this.exportLoading = false;
        Message({
          message: '导出成功',
          type: 'success'
        })
        this.exportOpen = false;
      }).catch(() => {
      })
    },

    /**
     * 组织数据同步
     */
    deptPushDataClick() {
      this.$confirm('是否把组织数据同步到市政通系统', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          hrmDeptPushDataAPI().then(res => {
            Message({
              message: '同步成功',
              type: 'success'
            })
          })
            .catch(() => {
            })
        })
        .catch(() => {
        })
    },

    /**
     * 组织数据同步
     */
    gzwDeptPushDataClick() {
      this.$confirm('是否把组织数据同步到国资委人资管理系统', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          hrmEmployeeGzwDeptSyncAPI().then(res => {
            Message({
              message: '同步成功',
              type: 'success'
            })
          })
            .catch(() => {
            })
        })
        .catch(() => {
        })
    },

    /**
     * 列表点击 详情
     */
    handleRowClick(row, column, event) {
      if (this.detailAuth) {
        this.detailId = row.deptId
        this.detailShow = true
      }
    },

    /** ****组织图 */
    renderContent(h, data) {
      return `${data.name}（${data.totalNum}）`
    },

    orgTreeClass(data) {
      if(data.level == 1) {
        return 'org-tree-spec'
      }
      if(data.level == 2 && data.expand === true) {
        return 'org-tree-spec'
      }
      return {
        1: 'org-tree-company',
        2: 'org-tree-department'
      }[data.deptType]
    },
    orgTreeClick(e, data) {
      const dom = e.target
      if(dom.tagName === 'SPAN' && dom.classList.contains('org-tree-node-btn')){
        return
      }
      this.handleRowClick(data)
    },
    collapse(list) {
      var _this = this;
      let isTopCollapse = false
      if(list.length && list[0].level == 2) {
        isTopCollapse =  true
      }
      list.forEach(function(child) {
        if (child.expand) {
          child.expand = false;
        }
        if(isTopCollapse) {
          child.hidden = false
        }
        child.children && _this.collapse(child.children);
      });
    },
    onExpand(e,data) {
      let isExpand = false // 是否展开
      if ("expand" in data) {
        data.expand = !data.expand;
        isExpand = data.expand
        if (!data.expand && data.children) {
          this.collapse(data.children);
        }
      } else {
        this.$set(data, "expand", true);
        isExpand = true
      }
      if(isExpand && data.level == '2') {
        this.setTreeHidden(true, data.code)
      } else if(data.level == '2') {
        this.setTreeHidden(false)
      }
    },
    setTreeHidden(hidden, uniCode) {
      this.orgTreeData.children.forEach(item => {
        this.$set(item, 'hidden', hidden)
        if (item.code === uniCode) {
          this.$set(item, 'hidden', false)
        }
      })
    },
    expandAll(expand, arr) {
      arr.forEach(item => {
        if(item.children && item.children.length) {
          this.$set(item, 'expand', expand)
          this.expandAll(expand, item.children)
        }
      })
    },
    expandOnlyUnit() {
      this.expandAll(false, this.orgTreeData.children)
      this.$set(this.orgTreeData, 'expand', true)
    },
    formatOrgTree(isOnlyCompany){
      let orgInfo = this.deepClone(this.list[0])
      delete orgInfo.empIds
      console.log(orgInfo)
      debugger
      orgInfo.expand = true
      orgInfo.children = this.filterDataByType(orgInfo.children, isOnlyCompany)
      this.orgTreeData = orgInfo
    },
    deepClone(sourceObj) {
      let cache = [];
      let json_str = JSON.stringify(sourceObj, function(key, value) {
        if (typeof value === 'object' && value !== null) {
          if (cache.indexOf(value) !== -1) {
            return;
          }
          cache.push(value);
        }
        return value;
      });
      cache = null;	//释放cache
      return JSON.parse(json_str)
    },
    filterDataByType(arr, isOnlyCompany) {
      let result = []
      arr.forEach(item => {
        if(isOnlyCompany) {
          if (item.deptType == '1') {
            result.push(item)
            if (item.children && item.children.length > 0) {
              item.children = this.filterDataByType(item.children, isOnlyCompany)
            }
          }
        } else {
          result.push(item)
          if (item.children && item.children.length > 0) {
            item.children = this.filterDataByType(item.children, isOnlyCompany)
          }
        }
      })
      return result
    },
    showTypeChange(val) {
      if(val === 'all') {
        // this.orgTreeData = this.filterDataByType(objDeepCopy(this.list[0]), false)
        // this.expandOnlyUnit()
        // this.setTreeHidden(false)
        this.formatOrgTree(false)
      } else if (val === 'onlyUnit') {
        this.formatOrgTree(true)
        // this.orgTreeData = this.filterDataByType(objDeepCopy(this.list[0]), true)
        // this.expandOnlyUnit()
        // this.setTreeHidden(false)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  width: 100%;

  .xr-header {
    margin-bottom: 20px;

    ::v-deep .xr-header__ft {
      top: 0;
      line-height: 34px;
    }
  }

  .search-button {
    border: none;

    &.is-select {
      color: white;
      background: $--color-primary;
    }
  }

  &-main {
    &.is-org {
      text-align: center;
    }
  }

  ::v-deep .el-radio-button__inner {
    padding: 7px 15px;
  }

  .wk-org-tree {
    overflow: auto;
  }
  // 修改对话框高度
  .showAll_dialog {
    overflow: hidden;
    ::v-deep .el-dialog {
      margin: 0 auto !important;
      height: 70%;
      overflow: hidden;
      background-color: black;
    }
  }
}
</style>
